<template>
  <v-container>
    <v-dialog
      v-model="dialog"
      :max-width="dialogWidth"
    >
      <v-card>
        <v-card-title>
          <span class="text-h3">
            {{ lanChar.ruleConfig.MCGroupInfoEditTitle }}
          </span>
        </v-card-title>
        <v-card-subtitle>
          <span class="text-h3 text--primary font-weight-medium">
            {{ groupInfo.GroupName }}
          </span>
        </v-card-subtitle>
        <v-divider />
        <v-divider />
        <v-divider />
        <v-divider />
        <v-divider />
        <v-card-text v-if="mode==='tcp-server-uri'">
          <v-container class="text-h4 text--primary font-weight-medium">
            <v-row
              v-for="(v, i) in groupInfo.TcpServerInfo.Uris"
              :key="i"
              dense
              align="center"
            >
              <span class="pr-5">
                {{ lanChar.ruleConfig.MCGroupRuleTcpUri }}
              </span>
              <v-text-field
                v-model.trim="v.Uri"
                class="pr-5"
                solo-inverted
                dense
                hide-details="auto"
                :rules="[rules.tcpUri]"
                :hint="lanChar.ruleConfig.MCGroupRuleTcpUriInputHint"
              />
              <v-checkbox
                v-model="isSave"
                class="pr-2"
                color="secondary"
                hide-details
                :label="lanChar.checkSave"
                style="height: 100%"
              />
              <v-btn
                class="mr-0"
                color="secondary"
                min-width="90"
                @click="confirmDialog((v.Uri === ''?lanChar.ruleConfig.MCGroupRuleDelTCPUriConfirm:lanChar.ruleConfig.MCGroupRuleUpdateTCPUriConfirm)+v.Uri+'?', lanChar.ruleConfig.MCGroupRuleTcpUri+':'+v.Uri, updateServerUri, {Uri: v.Uri, OldUri: groupInfoBak.TcpServerInfo.Uris[i].Uri})"
              >
                <v-icon class="pr-1">
                  mdi-note-edit-outline mdi-18px
                </v-icon>
                {{ lanChar.operateMod }}
              </v-btn>
            </v-row>
            <v-divider />
          </v-container>
        </v-card-text>
        <v-card-text v-if="mode==='udp-server-uri'">
          <v-container class="text-h4 text--primary font-weight-medium">
            <v-row
              v-for="(v, i) in groupInfo.UdpServerInfo.Uris"
              :key="i"
              dense
              align="center"
            >
              <span class="pr-5">
                {{ lanChar.ruleConfig.MCGroupRuleUdpUri }}
              </span>
              <v-text-field
                v-model.trim="v.Uri"
                class="pr-5"
                solo-inverted
                dense
                hide-details="auto"
                :rules="[rules.udpUri]"
                :hint="lanChar.ruleConfig.MCGroupRuleUdpUriInputHint"
              />
              <v-checkbox
                v-model="isSave"
                class="pr-2"
                color="secondary"
                hide-details
                :label="lanChar.checkSave"
                style="height: 100%"
              />
              <v-btn
                class="mr-0"
                color="secondary"
                min-width="90"
                @click="confirmDialog((v.Uri === ''?lanChar.ruleConfig.MCGroupRuleDelUDPUriConfirm:lanChar.ruleConfig.MCGroupRuleUpdateUDPUriConfirm)+v.Uri+'?', lanChar.ruleConfig.MCGroupRuleUdpUri+':'+v.Uri, updateServerUri, {Uri: v.Uri, OldUri: groupInfoBak.UdpServerInfo.Uris[i].Uri})"
              >
                <v-icon class="pr-1">
                  mdi-note-edit-outline mdi-18px
                </v-icon>
                {{ lanChar.operateMod }}
              </v-btn>
            </v-row>
            <v-divider />
          </v-container>
        </v-card-text>
        <v-card-text v-if="mode==='terminal-uri'">
          <v-container class="text-h4 text--primary font-weight-medium">
            <v-row
              dense
              align="center"
            >
              <span>
                {{ lanChar.ruleConfig.MCGroupRuleClientUri }}
              </span>
              <v-spacer />
              <v-checkbox
                v-model="isSave"
                class="pr-2"
                color="secondary"
                hide-details
                :label="lanChar.checkSave"
                style="height: 100%"
              />
            </v-row>
            <v-row
              dense
            >
              <v-col
                cols="12"
                sm="12"
              >
                <v-text-field
                  v-for="(v, i) in groupInfo.TerminalInfo.Uris"
                  :key="i"
                  v-model.trim="v.Uri"
                  solo-inverted
                  dense
                  hide-details="auto"
                  append-icon="mdi-delete-outline"
                  append-outer-icon="mdi-pen"
                  :prefix="(v.Role===0)?'R-S: ':'R-C: '"
                  :rules="[rules.tcpUdpUri]"
                  :hint="lanChar.ruleConfig.MCGroupRuleTcpUdpUriInputHint"
                  @click:append="confirmDialog(lanChar.ruleConfig.MCGroupRuleDelTerminalUriConfirm+v.Uri+'?', lanChar.ruleConfig.MCGroupRuleClientUri+':'+v.Uri, delTerminalUri, {Uri: v.Uri})"
                  @click:append-outer="statusDialog('McTerminalUriEditDialog', {val: groupInfo, index: i, mode: 'mod'})"
                />
              </v-col>
            </v-row>
            <v-row
              dense
              align="center"
            >
              <v-tooltip
                v-if="mode !== 'view'"
                top
              >
                <template v-slot:activator="{ on, attrs }">
                  <v-btn
                    color="primary"
                    dark
                    width="100%"
                    v-bind="attrs"
                    v-on="on"
                    @click="statusDialog('McTerminalUriEditDialog', {val: groupInfo, mode: 'add'})"
                  >
                    <v-icon left>
                      mdi-plus-circle
                    </v-icon>
                    <span>{{ lanChar.ruleConfig.MCGroupRuleAddClientUriButtonDescp }}</span>
                  </v-btn>
                </template>
                <span>{{ lanChar.ruleConfig.MCGroupRuleAddClientUriButtonHint }}</span>
              </v-tooltip>
            </v-row>
            <v-divider />
          </v-container>
        </v-card-text>
        <v-card-actions>
          <v-spacer />
          <v-btn
            color="blue darken-1"
            text
            @click="dialog = false"
          >
            {{ lanChar.operateClose }}
          </v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>
    <material-snackbar-tip
      v-model="snackbarDescp.snackbar"
      :type="snackbarDescp.snackbarType"
      :timeout="snackbarDescp.snackbarTimeout"
      v-bind="{
        bottom: true,
        right: true
      }"
      :text="snackbarDescp.snackbarContent"
    />
    <alert-dialog
      v-model="alert.dialog"
      :title="alert.title"
      :msg="alert.msg"
    />
    <confirm-dialog
      v-model="confirm.dialog"
      :title="confirm.content.title"
      :msg="confirm.content.msg"
      :callback="confirm.operate.callback"
      :input="confirm.operate.input"
    />
    <mc-terminal-uri-edit-dialog
      v-model="status.mcTerminalUriEditDialog"
      :input="status.operate.input"
    />
  </v-container>
</template>

<script>
  import globalDef from '@/util/globals'
  import lan from '@/util/lan-char'
  import * as mcAxios from '@/util/mcaxios'
  export default {
    name: 'McUriEditDialog',
    props: {
      value: Boolean,
      input: Object,
    },
    data () {
      return {
        lanChar: lan.GetLan(),
        dialog: this.value,
        statusTimer: 0,
        dialogWidth: 1000, // document.body.clientWidth ||
        groupInfo: {
          GroupName: '',
          TcpServerInfo: {
            Uris: [
              { Uri: '' },
            ],
            ConnectionNum: 0,
          },
          UdpServerInfo: {
            Uris: [
              { Uri: '' },
            ],
            ConnectionNum: 0,
          },
          TerminalInfo: {
            Uris: [
              { Uri: '' },
            ],
            ConnectionNum: 0,
          },
        },
        groupInfoBak: {},
        isSave: false,
        mode: 'tcp-server-uri',
        updateCnt: 0,
        rules: {
          required: value => !!value || this.lanChar.checkRequired,
          counter: value => value.length <= 20 || 'Max 20 characters',
          email: value => {
            const pattern = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
            return pattern.test(value) || this.lanChar.checkInvalidEMail
          },
          string: value => {
            const pattern = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))$/
            return pattern.test(value) || this.lanChar.checkInvalidString
          },
          tcpUri: value => {
            const pattern = /^(tcp:\/\/(([a-zA-Z\-0-9.]+))+\/[0-9]{1,5})|(^)$/
            return pattern.test(value) || this.lanChar.checkInvalidUri
          },
          udpUri: value => {
            const pattern = /^udp:\/\/(([a-zA-Z\-0-9.]+))+\/[0-9]{1,5}|(^)$/
            return pattern.test(value) || this.lanChar.checkInvalidUri
          },
          tcpUdpUri: value => {
            const pattern = /^tcp|udp:\/\/(([a-zA-Z\-0-9.]+))+\/[0-9]{1,5}|(^)$/
            return pattern.test(value) || this.lanChar.checkInvalidUri
          },
        },
        // snackbar data
        snackbarDescp: {
          snackbar: false,
          snackbarContent: 'snackbar content',
          snackbarTimeout: 2000,
          snackbarType: 'info',
        },
        // dialog data
        alert: {
          dialog: false,
          title: '',
          msg: '',
        },
        confirm: {
          dialog: false,
          content: {
            title: '',
            msg: '',
          },
          operate: {
            callback: null,
            input: null,
          },
        },
        status: {
          mcTerminalUriEditDialog: false,
          operate: {
            input: null,
          },
        },
      }
    },
    watch: {
      dialog (val, oldVal) {
        if (val === oldVal) return

        this.$emit('input', val)
        if (val === true) {
          this.startReflash()
        } else {
          clearInterval(this.statusTimer)
        }
      },
      value (val, oldVal) {
        if (val === oldVal) return

        this.dialog = val
      },
      input: {
        handler (val, oldVal) {
          if (val === oldVal) return
          if (val.val !== null && val.val !== undefined && val.val.GroupName !== undefined) {
            this.groupInfo = JSON.parse(JSON.stringify(val.val))
            this.groupInfoBak = JSON.parse(JSON.stringify(val.val))
          }
          this.mode = val.mode
        },
        deep: true,
      },
    },
    created () {
      globalDef.VueObject.$on('lanChange', lanChar => {
        this.lanChar = lanChar
      })
    },
    mounted () {
    },
    beforeDestroy () {
    },
    methods: {
      tipInfo (level, content, timeout) {
        this.snackbarDescp.snackbarType = level
        this.snackbarDescp.snackbarContent = content
        this.snackbarDescp.snackbarTimeout = timeout
        this.snackbarDescp.snackbar = true
      },
      alertInfo (title, content) {
        this.alert.dialog = true
        this.alert.title = title
        this.alert.msg = content
      },
      confirmDialog (title, msg, operate, data) {
        this.confirm.content.title = title
        this.confirm.content.msg = msg
        this.confirm.operate.callback = operate
        this.confirm.operate.input = data
        this.confirm.dialog = true
      },
      statusDialog (name, data) {
        this.status.operate.input = data
        if (name === 'McTerminalUriEditDialog') {
          this.status.mcTerminalUriEditDialog = true
        }
      },
      addTerminalUri () {
        this.groupInfo.TerminalInfo.Uris.push({ Uri: '' })
      },
      getMcGroupInfo () {
        const data = {
          request_type: 'mc group info get',
          instance_id: 'instance_id',
          sequence_no: 1000,
          data: {
            GroupName: this.groupInfo.GroupName,
          },
        }
        mcAxios.axiosGetConfig(data)
          .then((res) => {
            if (res.data.status === true) {
              this.groupInfo = {}
              this.groupInfo = res.data.data
              this.groupInfoBak = JSON.parse(JSON.stringify(this.groupInfo))
            } else {
              console.log('getMcGroupInfo get res fail')
            }
          })
          .catch((e) => {
            console.log('getMcGroupInfo get fail: ', e)
          })
      },
      updateServerUri (v) {
        if (String(this.groupInfo.GroupName) === '') {
          this.alertInfo(this.lanChar.alertInfoTitleInputError, this.lanChar.alertInfoParamError)
          return
        }
        const dataDel = {
          request_type: 'mc group server update',
          instance_id: 'instance_id',
          sequence_no: 1000,
          data: {
            GroupName: this.groupInfo.GroupName,
            Uri: v.Uri,
            OldUri: v.OldUri,
            IsSave: this.isSave,
          },
        }
        mcAxios.axiosSetConfig(dataDel)
          .then((res) => {
            if (res.data.status === true) {
              this.tipInfo('success', this.lanChar.tipInfoOperateSuccess, globalDef.TIPINFO_DISPLAY_DURATION)
            } else {
              this.tipInfo('info', this.lanChar.tipInfoOperateRespFail + res.data.msg, globalDef.TIPINFO_DISPLAY_DURATION)
            }
            this.getMcGroupInfo()
          })
          .catch((e) => {
            this.tipInfo('error', this.lanChar.tipInfoOperateRequestFail + e, globalDef.TIPINFO_DISPLAY_DURATION)
          })
      },
      delTerminalUri (v) {
        if (String(this.groupInfo.GroupName) === '' ||
          v === '') {
          this.alertInfo(this.lanChar.alertInfoTitleInputError, this.lanChar.alertInfoParamError)
          return
        }

        const dataSet = {
          request_type: 'mc group terminal del',
          instance_id: 'instance_id',
          sequence_no: 1000,
          data: {
            GroupName: this.groupInfo.GroupName,
            Uri: v.Uri,
            IsSave: this.isSave,
          },
        }
        mcAxios.axiosSetConfig(dataSet)
          .then((res) => {
            if (res.data.status === true) {
              this.tipInfo('success', this.lanChar.tipInfoOperateSuccess, globalDef.TIPINFO_DISPLAY_DURATION)
            } else {
              this.tipInfo('info', this.lanChar.tipInfoOperateRespFail + res.data.msg, globalDef.TIPINFO_DISPLAY_DURATION)
            }
            this.getMcGroupInfo()
          })
          .catch((e) => {
            this.tipInfo('error', this.lanChar.tipInfoOperateRequestFail + e, globalDef.TIPINFO_DISPLAY_DURATION)
          })
      },
      startReflash () {
        clearInterval(this.statusTimer)
        this.statusTimer = setInterval(this.getMcGroupInfo, globalDef.STATUS_QUERY_INTERVAL)
      },
    },
  }
</script>
